<?php
//------- logistic wxapp -------
namespace app\logi\controller;

use cmf\controller\AdminBaseController;
use app\logi\model\LogiPostModel;
use app\logi\service\PostService;
use app\logi\model\LogiCategoryModel;
use app\logi\model\LogiPriceModel;
use app\logi\model\LogiExpressModel;
use think\Db;

class AdminLogiController extends AdminBaseController {
    /**
     * 订单列表
     * @adminMenu(
     *     'name'   => '订单管理',
     *     'parent' => 'logi/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '订单列表',
     *     'param'  => ''
     * )
     */
    public function index() {
        $param = $this->request->param();
        $categoryId = $this->request->param('category', 0, 'intval');

        $postService = new PostService();
        $data        = $postService->adminPostList($param);
        $data->appends($param);

        $logiCategoryModel = new LogiCategoryModel();
        $categoryTree        = $logiCategoryModel->adminCategoryTree($categoryId);

        $mail_arr = db::name('logiMailStatus')->where(['status'=>1])->select();

        $this->assign('start_time', isset($param['start_time']) ? $param['start_time'] : '');
        $this->assign('end_time', isset($param['end_time']) ? $param['end_time'] : '');
        $this->assign('keyword', isset($param['keyword']) ? $param['keyword'] : '');
        $this->assign('mail_status', isset($param['mail_status']) ? $param['mail_status'] : '');
        $this->assign('res', $data->items());
        $this->assign('category_tree', $categoryTree);
        $this->assign('category', $categoryId);
        $this->assign('mail_arr', $mail_arr);
        $this->assign('page', $data->render());

        return $this->fetch();
    }

    /**
     * 添加订单
     * @adminMenu(
     *     'name'   => '添加订单',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加订单',
     *     'param'  => ''
     * )
     */
    public function add() {
        $logiPriceModel = new LogiPriceModel();
        $price = $logiPriceModel->where(['status'=>1])->select();
        $this->assign('price', $price);
        return $this->fetch();
    }

    /**
     * 添加订单提交
     * @adminMenu(
     *     'name'   => '添加订单提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加订单提交',
     *     'param'  => ''
     * )
     */
    public function addPost() {
        if ($this->request->isPost()) {
            $data   = $this->request->param();

            //状态只能设置默认值。发布
            $data['post']['post_status'] = 1;
            $data['post']['mail_status'] = 1;  //配送状态，由express更新
            //$data['post']['post_title'] = date('ymdHis').'-'.$data['user_name'].'-'.$data['post']['code'];
            // if (!isset($data['post']['mail_type']) or empty($data['post']['mail_type'])) {
            //     $data['post']['mail_type'] = 2;
            // }
            $data['post']['mail_type'] = 1;
            if (isset($data['post']['more']['total']) and !empty($data['post']['more']['total'])) {
                $data['post']['price'] = $data['post']['more']['total'];
            }

            $result = $this->validate($data['post'], 'AdminLogi');
            if ($result !== true) {
                $this->error($result);
            }
            if (!isset($data['post']['categories']) or empty($data['post']['categories'])) {
                $data['post']['categories'] = 0;
            }

            $logiPostModel = new LogiPostModel();
            $logiPostModel->adminAddLogi($data['post'], $data['post']['categories']);

            //发送微信消息
            $push = [
                'name'=>$data['post']['post_title'],
                'user_id'=>$data['post']['user_id'],
                'station'=>$data['post']['more']['station'],
                'user_addr'=>$data['post']['more']['user_addr'],
                'receive'=>$data['post']['receive'],
                'contact'=>$data['post']['contact'],
                'total'=>$data['post']['price'],
                'status_name'=>'待支付',
            ];
            cmf_push_msg($push);

            $this->success('添加成功!', url('AdminLogi/index'));
        }

    }

    /**
     * 编辑订单
     * @adminMenu(
     *     'name'   => '编辑订单',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑订单',
     *     'param'  => ''
     * )
     */
    public function edit() {
        $id = $this->request->param('id', 0, 'intval');

        $logiPostModel = new LogiPostModel();
        $post            = $logiPostModel->where('id', $id)->find();
        $postCategories  = $post->categories()->alias('a')->column('a.name', 'a.id');
        $postCategoryIds = implode(',', array_keys($postCategories));
        $post['status_name'] = Db::name('logiStatus')->where( ['id'=>$post['post_status']] )->value('name');

        $logiPriceModel = new LogiPriceModel();
        $price = $logiPriceModel->where(['status'=>1])->select();
        $this->assign('price', $price);

        $this->assign('post', $post);
        $this->assign('post_categories', $postCategories);
        $this->assign('post_category_ids', $postCategoryIds);

        return $this->fetch();
    }

    /**
     * 编辑订单提交
     * @adminMenu(
     *     'name'   => '编辑订单提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑订单提交',
     *     'param'  => ''
     * )
     */
    public function editPost() {
        if ($this->request->isPost()) {
            $data   = $this->request->param();

            $post   = $data['post'];
            // if (!isset($data['post']['mail_type']) or empty($data['post']['mail_type'])) {
            //     $data['post']['mail_type'] = 2;
            // }
            $data['post']['mail_type'] = 1;
            if (isset($data['post']['more']['total']) and !empty($data['post']['more']['total'])) {
                $data['post']['price'] = $data['post']['more']['total'];
            }
            $result = $this->validate($post, 'AdminLogi');
            if ($result !== true) {
                $this->error($result);
            }

            if (!isset($data['post']['categories']) or empty($data['post']['categories'])) {
                $data['post']['categories'] = 0;
            }

            $logiPostModel = new LogiPostModel();
            $logiPostModel->adminEditLogi($data['post'], $data['post']['categories']);

            $this->success('保存成功!');

        }
    }

    /**
     * 订单删除
     * @adminMenu(
     *     'name'   => '订单删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '订单删除',
     *     'param'  => ''
     * )
     */
    public function delete() {
        $param         = $this->request->param();
        $logiPostModel = new LogiPostModel();

        if (isset($param['id'])) {
            $id           = $this->request->param('id', 0, 'intval');
            $resultlogi = $logiPostModel
                ->where(['id' => $id])
                ->update(['delete_time' => time()]);
            if ($resultlogi) {
                Db::name('logi_category_post')->where(['post_id'=>$id])->update(['status'=>0]);
                //Db::name('logi_tag_post')->where(['post_id'=>$id])->update(['status'=>0]);
            }
            $this->success("删除成功！", '');

        }

        if (isset($param['ids'])) {
            $ids     = $this->request->param('ids/a');
            $result  = $logiPostModel->where(['id' => ['in', $ids]])->update(['delete_time' => time()]);
            if ($result) {
                Db::name('logi_category_post')->where(['post_id' => ['in', $ids]])->update(['status'=>0]);
                //Db::name('logi_tag_post')->where(['post_id' => ['in', $ids]])->update(['status'=>0]);
                $this->success("删除成功！", '');
            }
        }
    }


    /**
     * 订单发布
     * @adminMenu(
     *     'name'   => '订单发布',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '订单发布',
     *     'param'  => ''
     * )
     */
    public function publish() {
        $param           = $this->request->param();
        $logiPostModel = new LogiPostModel();

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');
            $logiPostModel->where(['id' => ['in', $ids]])->update(['post_status' => 1, 'published_time' => time()]);

            $this->success("发布成功！", '');
        }

        if (isset($param['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');
            $logiPostModel->where(['id' => ['in', $ids]])->update(['post_status' => 0]);

            $this->success("取消发布成功！", '');
        }

    }

    /**
     * 订单付款状态
     * @adminMenu(
     *     'name'   => '订单付款状态',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '订单付款状态',
     *     'param'  => ''
     * )
     */
    public function top() {
        $param           = $this->request->param();
        $logiPostModel = new LogiPostModel();

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');
            $logiPostModel->where(['id' => ['in', $ids]])->update(['pay_status' => 1]);
            $this->success("更新成功！", '');

        }

        if (isset($_POST['ids']) && isset($param["no"])) {
            $ids = $this->request->param('ids/a');
            $logiPostModel->where(['id' => ['in', $ids]])->update(['pay_status' => 2]);
            $this->success("更新成功！", '');
        }
    }

    /**
     * 订单快递详情列表
     * @adminMenu(
     *     'name'   => '订单快递详情列表',
     *     'parent' => 'index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '订单快递详情列表',
     *     'param'  => ''
     * )
     */
    public function express() {
        $param = $this->request->param();
        if (isset($param['id']) and !empty($param['id'])) {
            session('logi_id',$param['id']);

            $model = new LogiExpressModel();
            $join = [
                ['__LOGI_MAIL_STATUS__ m', 'a.status = m.id','left'],
            ];
            $field = 'a.*,m.name as m_name';
            $data = $model->alias('a')->join($join)->where(['a.logi_id'=>$param['id'] ])->order('a.id desc')->field($field)->paginate(10);
            $data->appends($param);

            $this->assign('res', $data->items());
            $this->assign('page', $data->render());

            return $this->fetch();
        }
        
    }

    /**
     * 添加快递信息
     * @adminMenu(
     *     'name'   => '添加快递信息',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加快递信息',
     *     'param'  => ''
     * )
     */
    public function expadd() {
        $model = new LogiExpressModel();
        $arrStatus = db::name('logiMailStatus')->where(['status'=>1])->select();
        $this->assign("arrStatus", $arrStatus);
        $codes = db::name('logiExpressCode')->where(['status'=>1])->select();
        $this->assign("codes", $codes);
        return $this->fetch();
    }

    /**
     * 添加快递信息提交
     * @adminMenu(
     *     'name'   => '添加快递信息提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加快递信息提交',
     *     'param'  => ''
     * )
     */
    public function expAddPost() {
        $param = $this->request->param();
        $param['logi_id'] = session('logi_id');
        if (!isset($param['express_num']) or empty($param['express_num'])) {
            $this->error('请输入快递单号');
        }

        $model = new LogiExpressModel();
        $model->isUpdate(false)->allowField(true)->save($param);
        $postModel = new LogiPostModel();
        $postModel->where(['id'=>$param['logi_id']])->update(['mail_status'=>$param['status']]);

        $this->success(lang("SAVE_SUCCESS"),url('AdminLogi/express',['id'=>$param['logi_id']]));
    }

    /**
     * 快递信息标签
     * @adminMenu(
     *     'name'   => '快递信息标签',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '快递信息标签',
     *     'param'  => ''
     * )
     */
    public function expedit() {
        $id = $this->request->param('id', 0, 'intval');
        if ($id > 0) {
            $model = new LogiExpressModel();
            $res = $model::get($id)->toArray();
            $this->assign($res);

            $arrStatus = db::name('logiMailStatus')->where(['status'=>1])->select();
            $this->assign("arrStatus", $arrStatus);

            $codes = db::name('logiExpressCode')->where(['status'=>1])->select();
            $this->assign("codes", $codes);

            return $this->fetch();
        } else {
            $this->error('操作错误!');
        }
    }

    /**
     * 快递信息提交
     * @adminMenu(
     *     'name'   => '快递信息提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '快递信息提交',
     *     'param'  => ''
     * )
     */
    public function expEditPost() {
        $param = $this->request->param();
        $param['logi_id'] = session('logi_id');

        $model = new LogiExpressModel();
        $model->isUpdate(true)->allowField(true)->save($param);

        $postModel = new LogiPostModel();
        $postModel->where(['id'=>$param['logi_id']])->update(['mail_status'=>$param['status']]);

        $this->success(lang("SAVE_SUCCESS"),url('AdminLogi/express',['id'=>$param['logi_id']]));

    }

    /**
     * 快递信息删除
     * @adminMenu(
     *     'name'   => '快递信息删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '快递信息删除',
     *     'param'  => ''
     * )
     */
    public function expdelete() {
        $param = $this->request->param();
        $model = new LogiExpressModel();
        if (isset($param['id'])) {
            $id = $this->request->param('id', 0, 'intval');
            $model->where(['id' => $id])->delete();
            $this->success("删除成功！", '');
        }
    }

    public function showSourceData() {
        $param = $this->request->param();
        $param['table'] = isset($param['table'])?$param['table']:'user';
        $param['tid'] = isset($param['tid'])?$param['tid']:'id';
        $param['tname'] = isset($param['tname'])?$param['tname']:'1';
        $db = Db::name($param['table']);
        $where = [ $param['tid']=>$param['tname'] ];
        $res = $db->where($where)->field('*')->select();
        var_dump($res);exit;
    }
}
